package io.zhiller.camerademo.ui.screen

import android.util.Log
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.lifecycle.compose.LocalLifecycleOwner
import io.zhiller.camerademo.camera.barcode.BarcodeAnalyzer
import io.zhiller.camerademo.camera.barcode.ScannerType
import io.zhiller.camerademo.camera.barcode.TextAnalyzer

/**
 * Composable函数，用于显示图片扫描器界面
 *
 * @param scannerType 扫描器类型，决定是使用条形码扫描还是文本扫描
 */
@Composable
fun PicScannerScreen(
  scannerType: ScannerType
) {
  // 获取当前上下文
  val localContext = LocalContext.current
  // 获取当前生命周期所有者
  val lifecycleOwner = LocalLifecycleOwner.current
  // 记住相机提供者未来对象，避免每次都重新创建
  val cameraProviderFuture = remember {
    ProcessCameraProvider.getInstance(localContext)
  }

  // 创建Android视图，填充整个屏幕
  AndroidView(
    modifier = Modifier.fillMaxSize(),
    factory = { context ->
      // 创建预览视图
      val previewView = PreviewView(context)
      // 创建预览对象
      val preview = Preview.Builder().build()
      // 创建相机选择器，指定使用后置摄像头
      val selector = CameraSelector.Builder()
        .requireLensFacing(CameraSelector.LENS_FACING_BACK)
        .build()

      // 设置预览的表面提供者
      preview.setSurfaceProvider(previewView.surfaceProvider)

      // 创建图像分析对象
      val imageAnalysis = ImageAnalysis.Builder().build()
      // 设置图像分析器，根据scannerType选择条形码分析器或文本分析器
      imageAnalysis.setAnalyzer(
        ContextCompat.getMainExecutor(context),
        if (scannerType == ScannerType.BARCODE) {
          BarcodeAnalyzer(context)
        } else {
          TextAnalyzer(context)
        }
      )

      // 尝试获取相机提供者并绑定生命周期
      runCatching {
        cameraProviderFuture.get().bindToLifecycle(
          lifecycleOwner,
          selector,
          preview,
          imageAnalysis
        )
      }.onFailure {
        // 如果绑定失败，记录错误日志
        Log.e("CAMERA", "Camera bind error ${it.localizedMessage}", it)
      }
      // 返回预览视图
      previewView
    }
  )
}
